package com.sk.weichat.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sk.weichat.AppConstant;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.FriendHeadAdapter;
import com.sk.weichat.adapter.MultipleItemAdapter;
import com.sk.weichat.adapter.MyMultipleItem;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.PrivacySetting;
import com.sk.weichat.bean.RoomMember;
import com.sk.weichat.bean.User;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.GroupMessage;
import com.sk.weichat.bean.message.MucRoom;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.bean.redpacket.RedPacketNoticeBean;
import com.sk.weichat.bean.redpacket.RedPacketNoticeInfoBean;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.GroupMessageDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.db.dao.RedPacketNoticeDao;
import com.sk.weichat.db.dao.RoomMemberDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.PrivacySettingHelper;
import com.sk.weichat.helper.SharedPreferenceHelper;
import com.sk.weichat.pay.sk.SKPayActivity;
import com.sk.weichat.ui.MainActivity;
import com.sk.weichat.ui.base.EasyFragment;
import com.sk.weichat.ui.contacts.GroupMessageActivity;
import com.sk.weichat.ui.contacts.NewFriendActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.me.wallet.WalletNotificationsActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.ui.message.MessageCallActivity;
import com.sk.weichat.ui.message.MucChatActivity;
import com.sk.weichat.ui.message.TabFriendActivity;
import com.sk.weichat.ui.message.search.SearchActivity;
import com.sk.weichat.ui.nearby.UserListGatherActivity;
import com.sk.weichat.util.AppUtils;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.HtmlUtils;
import com.sk.weichat.util.HttpUtil;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.StringUtils;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.LCardView;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.view.VerifyDialog;
import com.sk.weichat.xmpp.ListenerManager;
import com.sk.weichat.xmpp.XmppConnectionManager;
import com.sk.weichat.xmpp.listener.AuthStateListener;
import com.sk.weichat.xmpp.listener.ChatMessageListener;
import com.swipemenulib.SwipeMenuLayout;
import com.umeng.commonsdk.debug.E;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;

/**
 * 消息界面
 * <p>
 * update by swy
 */
public class MessageFragment extends EasyFragment implements AuthStateListener, ChatMessageListener {
    // 消息界面在前台展示中就不响铃新消息，
    public static boolean foreground = false;
    private LinearLayout mNetErrorLl;
    private SmartRefreshLayout refreshLayout;
    private MultipleItemAdapter mAdapter;
    private FriendHeadAdapter mFriendHeadAdapter;

    private List<Friend> mFriendList;
    private List<MyMultipleItem> mItemList;
    private ArrayList<Friend> mUnReplyList;
    private List<Friend> mNewFriendList;
    private ArrayList<User> mHeadFriendList;

    // 上次刷新时间，限制过快刷新，
    private long refreshTime;
    private boolean timerRunning;

    private RelativeLayout layoutHead;//推荐好友布局
    private RelativeLayout headContent;//推荐好友
    private TextView headChange;
    private ImageView headArrow;

    private View view_notification;
    private LCardView lcard_open_group_tips;
    //    private RelativeLayout rl_open_group_tips;
    private Button btn_open_notification;
    private ImageView img_close_open_notification;


    // 刷新的定时器，限制过快刷新，
    private CountDownTimer timer = new CountDownTimer(1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            Log.e("notify", "计时结束，更新消息页面");
            timerRunning = false;
            refreshTime = System.currentTimeMillis();
            refresh();
        }
    };

    //更新数据广播接收
    private BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.isEmpty(action)) {
                return;
            }
            if (action.equals(com.sk.weichat.broadcast.OtherBroadcast.IsRead)) {//已读通知
                refresh();
            } else if (action.equals(MsgBroadcast.ACTION_MSG_UI_UPDATE)) {// 刷新页面
                long lastRefreshTime = refreshTime;
                long delta = System.currentTimeMillis() - lastRefreshTime;
                if (delta > TimeUnit.SECONDS.toMillis(1)) {
                    refreshTime = System.currentTimeMillis();
                    refresh();
                    MainActivity mMainActivity = (MainActivity) getActivity();
                    if (mMainActivity != null) {
                        new Handler().postDelayed(() -> mMainActivity.updateNumData(), 1000);

                    }
                } else if (!timerRunning) {
                    timerRunning = true;
                    timer.start();
                }
            } else if (action.equals(Constants.NOTIFY_MSG_SUBSCRIPT)) {
                Friend friend = (Friend) intent.getSerializableExtra(AppConstant.EXTRA_FRIEND);
                if (friend != null) {
                    clearSingleMessageNum(friend);
                }
            } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {// 网络发生改变
                if (!HttpUtil.isGprsOrWifiConnected(getActivity())) {
                    mNetErrorLl.setVisibility(View.VISIBLE);
                } else {
                    mNetErrorLl.setVisibility(View.GONE);
                }
            } else if (action.equals(Constants.NOT_AUTHORIZED)) {
//                mTvTitle.setText(getString(R.string.password_error));
            } else if (action.equals(MsgBroadcast.ACTION_WALLET_NOTICE)) {
                MyMultipleItem newMyItemType = setupWalletItem();
                int index = findWalletItemPosition(mItemList);
                // Log.e("lzs", "index:" + index);
                mItemList.set(index, newMyItemType);
                //排序
                Collections.sort(mItemList);
                //刷新
                mAdapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    protected int inflateLayoutId() {
        return R.layout.fragment_message;
    }

    @Override
    protected void onActivityCreated(Bundle savedInstanceState, boolean createView) {
        initActionBar();
        // 不能用createView判断不初始化，因为Fragment复用时老activity可能被销毁了，
        initView();
        loadFriendList();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        foreground = isVisibleToUser;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        foreground = !hidden;
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onPause() {
        foreground = false;
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        foreground = true;
        /*判断通知栏权限是否开启*/
        if (!AppUtils.isNotificationEnabled(mActivity) && !SharedPreferenceHelper.getNotificationTips(mActivity)) {
            view_notification.setVisibility(View.INVISIBLE);
            lcard_open_group_tips.setVisibility(View.VISIBLE);
        } else {
            view_notification.setVisibility(View.GONE);
            lcard_open_group_tips.setVisibility(View.GONE);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mUpdateReceiver != null) {
            Objects.requireNonNull(getActivity()).unregisterReceiver(mUpdateReceiver);
        }
        ListenerManager.getInstance().removeAuthStateChangeListener(this);
        ListenerManager.getInstance().removeChatMessageListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.tv_actionbar_title:
                // xmpp重连
                hardLine();
                break;

            case R.id.img_actionbar_clear:
                // 清除消息
                showClearUnReadDialog();
                break;

            case R.id.layout_message_search:
                //搜索
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;

            case R.id.img_actionbar_friend:
                // 通讯录
                startActivity(new Intent(getActivity(), TabFriendActivity.class));
                break;

            case R.id.img_actionbar_add:
                // 添加好友
                startActivity(new Intent(getActivity(), UserListGatherActivity.class));
                break;

            case R.id.net_error_ll:
                //网络错误
                startActivity(new Intent(Settings.ACTION_SETTINGS));
                break;
        }
    }

    @Override
    public void onMessageSendStateChange(int messageState, String msgId) {
        loadFriendList();
    }

    @Override
    public boolean onNewMessage(String fromUserId, ChatMessage message, boolean isGroupMsg) {
        return false;
    }


    /**
     * xmpp在线状态监听
     */
    @Override
    public void onAuthStateChange(int authState) {
        authState = XmppConnectionManager.mXMPPCurrentState;
//        if (mTvTitle == null) {
//            return;
//        }
        if (authState == 0 || authState == 1) {
            // 登录中
            //findViewById(R.id.pb_title_center).setVisibility(View.VISIBLE);
//            mTvTitle.setText(InternationalizationHelper.getString("JXMsgViewController_GoingOff"));
        } else if (authState == 2) {
            // 在线
            DialogHelper.dismissProgressDialog();
            MainActivity.isAuthenticated = true;
            //findViewById(R.id.pb_title_center).setVisibility(View.GONE);
//            mTvTitle.setText(InternationalizationHelper.getString("JXMsgViewController_OnLine"));
            mNetErrorLl.setVisibility(View.GONE);// 网络判断对部分手机有时会失效，坐下兼容(当xmpp在线时，隐藏网络提示)
        } else {
            // 离线
            DialogHelper.dismissProgressDialog();
            //findViewById(R.id.pb_title_center).setVisibility(View.GONE);
//            mTvTitle.setText(InternationalizationHelper.getString("JXMsgViewController_OffLine"));
        }
    }

    private void initActionBar() {
        TextView mTvTitle = findViewById(R.id.tv_actionbar_title);
        mTvTitle.setText("消息");

        /* 通知栏开启悬浮提示*/
        view_notification = findViewById(R.id.view_notification);
        lcard_open_group_tips = findViewById(R.id.lcard_open_group_tips);
        btn_open_notification = findViewById(R.id.btn_open_notification);
        img_close_open_notification = findViewById(R.id.img_close_open_notification);

        /*判断通知栏权限是否开启*/
        if (!AppUtils.isNotificationEnabled(mActivity) && !SharedPreferenceHelper.getNotificationTips(mActivity)) {
            view_notification.setVisibility(View.INVISIBLE);
            lcard_open_group_tips.setVisibility(View.VISIBLE);
        } else {
            view_notification.setVisibility(View.GONE);
            lcard_open_group_tips.setVisibility(View.GONE);
        }
        /*去开启通知栏权限*/
        btn_open_notification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                if (Build.VERSION.SDK_INT >= 26) {
                    // android 8.0引导
                    intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                    intent.putExtra("android.provider.extra.APP_PACKAGE", mActivity.getPackageName());
                } else if (Build.VERSION.SDK_INT >= 21) {
                    // android 5.0-7.0
                    intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                    intent.putExtra("app_package", mActivity.getPackageName());
                    intent.putExtra("app_uid", mActivity.getApplicationInfo().uid);
                } else {
                    // 其他
                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    intent.setData(Uri.fromParts("package", mActivity.getPackageName(), null));
                }
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        /*关闭悬浮提示*/
        img_close_open_notification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view_notification.setVisibility(View.GONE);
                lcard_open_group_tips.setVisibility(View.GONE);
                //保存 悬浮提示 已经提示过
                SharedPreferenceHelper.setNotificationTips(mActivity, true);
                ToastUtil.showToast(mActivity, "可到我的-设置-消息通知页面了解消息开启状态");

            }
        });

        appendClick(findViewById(R.id.img_actionbar_clear));//清除消息
        appendClick(findViewById(R.id.img_actionbar_friend));//通讯录
        appendClick(findViewById(R.id.img_actionbar_add));//添加好友


    }

    private void initView() {
        mItemList = new ArrayList<>();
        mUnReplyList = new ArrayList<>();//未回复
        mNewFriendList = new ArrayList<>();
        mHeadFriendList = new ArrayList<>();
        mNetErrorLl = findViewById(R.id.net_error_ll);
        mNetErrorLl.setOnClickListener(this);
        findViewById(R.id.layout_message_search).setOnClickListener(this);
        initMainRecyclerView();
        refreshLayout = findViewById(R.id.refresh_layout_msg_frg);
        refreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        refreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            //加载推荐好友
            loadUnKnowUserList();
            refresh();
        });

        ListenerManager.getInstance().addAuthStateChangeListener(this);
        ListenerManager.getInstance().addChatMessageListener(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MsgBroadcast.ACTION_MSG_UI_UPDATE);// 刷新页面Ui
        intentFilter.addAction(com.sk.weichat.broadcast.OtherBroadcast.IsRead);
        intentFilter.addAction(Constants.NOTIFY_MSG_SUBSCRIPT);// 刷新"消息"角标
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);// 网络发生改变
        intentFilter.addAction(Constants.NOT_AUTHORIZED);// XMPP密码错误
        intentFilter.addAction(MsgBroadcast.ACTION_WALLET_NOTICE);// 钱包通知
        getActivity().registerReceiver(mUpdateReceiver, intentFilter);

        //推荐好友（陌生人）
        loadUnKnowUserList();

    }

    private void initMainRecyclerView() {
        RecyclerView recyclerView = findViewById(R.id.recycler_msg_frg);
        LinearLayoutManager manager = new LinearLayoutManager(mActivity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        mAdapter = new MultipleItemAdapter(coreManager.getSelf().getUserId(), mItemList, mUnReplyList, mNewFriendList);

        addMainHeaderView();

        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setHasStableIds(true);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Friend friend = mItemList.get(position).getData();
                Intent intent;
                switch (view.getId()) {
                    case R.id.delete_tv:
                        //删除
                        clickItemDelete(adapter, view, position, friend);
                        break;
                    case R.id.read_unread_tv:
                        //标记为已读
                        clickItemMarkAsRead(view, friend);
                        break;
                    case R.id.top_tv:
                        //置顶
                        clickItemMarkAsTop(view, friend);
                        break;
                    case R.id.replay_iv://快速回复
                    case R.id.num_tv://点击未读消息图标也可以快速回复
                        quickReplay(adapter, friend);
                        break;
                    case R.id.layout_call_item:
                        //点击招呼消息
                        intent = new Intent(getActivity(), MessageCallActivity.class);
                        Objects.requireNonNull(getActivity()).startActivity(intent);
                        break;
                    case R.id.layout_relation_item:
                        //点击关系通知
                        clickItemRelation();
                        break;
                    case R.id.layout_group_item:
                        //点击群通知
                        clickItemGroup();
                        break;
                    case R.id.item_friend_warp:
                        //点击item
                        clickItemLayout(friend);
                        break;
                    case R.id.root_view:
                        //跳转通知列表
                        startActivity(new Intent(getActivity(), WalletNotificationsActivity.class));
                        recyclerView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                MyMultipleItem walletNotice = mItemList.get(findWalletItemPosition(mItemList));
                                //walletNotice.setTime(-1);
                                walletNotice.setCount(0);
                                Collections.sort(mItemList);
                                adapter.notifyDataSetChanged();
                                //更新消息
                                MainActivity activity = (MainActivity) getActivity();
                                if (activity != null) {
                                    activity.updateNumData();
                                }
                            }
                        }, 1000);
                        break;
                }
            }
        });
        recyclerView.setAdapter(mAdapter);
    }

    private void clickItemLayout(Friend friend) {
        Intent intent;
        hardLine();
        clearSingleMessageNum(friend);
        intent = new Intent();
        if (friend.getRoomFlag() == 0) { // 个人
            if (TextUtils.equals(friend.getUserId(), Friend.ID_SK_PAY)) {
                intent.setClass(getActivity(), SKPayActivity.class);
            } else {
                intent.setClass(getActivity(), ChatActivity.class);
                intent.putExtra(ChatActivity.FRIEND, friend);
            }
        } else {
            intent.setClass(getActivity(), MucChatActivity.class);
            intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
            intent.putExtra(AppConstant.EXTRA_NICK_NAME, friend.getNickName());
        }

        intent.putExtra(Constants.NEW_MSG_NUMBER, friend.getUnReadNum());
        startActivity(intent);
    }

    private void clickItemRelation() {
        if (mNewFriendList.size() > 0) {
            FriendDao.getInstance().markUserMessageRead(coreManager.getSelf().getUserId(), Friend.ID_NEW_FRIEND_MESSAGE);
            MainActivity activity = (MainActivity) getActivity();
            if (activity != null) {
                activity.updateNumData();
            }
            mNewFriendList.get(0).setUnReadNum(0);
            mAdapter.notifyDataSetChanged();
        }
        Intent intentNewFriend = new Intent(getActivity(), NewFriendActivity.class);
        getActivity().startActivity(intentNewFriend);
    }

    private void clickItemGroup() {

        GroupMessageDao.getInstance().markUserMessageRead(coreManager.getSelf().getUserId());
        MsgBroadcast.broadcastMsgUiUpdate(getActivity());

        Intent intentNewFriend = new Intent(getActivity(), GroupMessageActivity.class);
        getActivity().startActivity(intentNewFriend);

    }

    /**
     * 点击item标记为置顶
     *
     * @param view
     * @param friend
     */
    public void clickItemMarkAsTop(View view, Friend friend) {
        if (friend.getTopTime() == 0) {
            FriendDao.getInstance().updateTopFriend(friend.getUserId(), friend.getTimeSend());
        } else {
            FriendDao.getInstance().resetTopFriend(friend.getUserId());
        }
        loadFriendList();
        ((SwipeMenuLayout) view.getParent()).quickClose();
    }

    /**
     * 点击item标记为已读
     *
     * @param view
     * @param friend
     */
    public void clickItemMarkAsRead(View view, Friend friend) {
        if (friend.getUnReadNum() > 0) {
            clearSingleMessageNum(friend);
        } else {
            FriendDao.getInstance().markUserMessageUnRead(friend.getOwnerId(), friend.getUserId());
            MsgBroadcast.broadcastMsgNumUpdate(MyApplication.getInstance(), true, 1);
            MsgBroadcast.broadcastMsgUiUpdate(MyApplication.getInstance());
        }
        ((SwipeMenuLayout) view.getParent()).quickClose();
    }

    /**
     * 点击item删除
     *
     * @param adapter
     * @param view
     * @param position
     * @param friend
     */
    public void clickItemDelete(BaseQuickAdapter adapter, View view, int position, Friend friend) {
        String mLoginUserId = coreManager.getSelf().getUserId();
        if (friend.getRoomFlag() == 0) {
            // 如果是普通的人，从好友表中删除最后一条消息的记录，这样就不会查出来了
            FriendDao.getInstance().resetFriendMessage(mLoginUserId, friend.getUserId());
            // 消息表中删除
            ChatMessageDao.getInstance().deleteMessageTable(mLoginUserId, friend.getUserId());
        } else {
            // 从消息表删除
            FriendDao.getInstance().resetFriendMessage(mLoginUserId, friend.getUserId());
        }
        if (friend.getUnReadNum() > 0) {
            MsgBroadcast.broadcastMsgNumUpdate(getActivity(), false, friend.getUnReadNum());
        }
        mItemList.remove(position);
        adapter.notifyItemRemoved(position + 1);
        adapter.notifyItemRangeChanged(position, mItemList.size() - (position + 1));
        ((SwipeMenuLayout) view.getParent()).quickClose();
    }

    /**
     * 添加头部（换一换功能）
     */
    private void addMainHeaderView() {
        View friendHeadView = LayoutInflater.from(getActivity()).inflate(R.layout.head_friend_messagefragment, null, false);

        RecyclerView headRecyclerView = friendHeadView.findViewById(R.id.recyclerview_head_friend);
        LinearLayoutManager headManager = new LinearLayoutManager(getActivity());
        headManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        headRecyclerView.setLayoutManager(headManager);
        mFriendHeadAdapter = new FriendHeadAdapter(R.layout.item_friend_recyclerview, mHeadFriendList);
        headRecyclerView.setAdapter(mFriendHeadAdapter);

        layoutHead = friendHeadView.findViewById(R.id.layout_head);
        //判断后台是否关闭推荐附近好友功能 0不关闭 1已关闭
        if (coreManager.readConfigBean().getIsCloseRecommend() == 0) {
            layoutHead.setVisibility(View.VISIBLE);
        } else {
            layoutHead.setVisibility(View.GONE);
        }
        headContent = friendHeadView.findViewById(R.id.layout_head_content);
        headArrow = friendHeadView.findViewById(R.id.img_head_arrow);
        headChange = friendHeadView.findViewById(R.id.tv_head_change);

        mFriendHeadAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.layout_call_item:
                        Intent intent = new Intent(requireActivity(), PersonalCenterActivity.class);
                        intent.putExtra(AppConstant.EXTRA_USER_ID, mHeadFriendList.get(position).getUserId());
                        requireActivity().startActivity(intent);
                        break;
                }
            }
        });

        //换一换
        headChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadUnKnowUserList();
            }
        });

        headArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (View.VISIBLE == headContent.getVisibility()) {
                    mFriendHeadAdapter.notifyDataSetChanged();
                    headArrow.setBackgroundResource(R.drawable.imessage_icon_arrow2);
                    headChange.setVisibility(View.GONE);
                    headContent.setVisibility(View.GONE);
                } else {
                    mFriendHeadAdapter.notifyDataSetChanged();
                    headArrow.setBackgroundResource(R.drawable.imessage_icon_arrow);
                    headChange.setVisibility(View.VISIBLE);
                    headContent.setVisibility(View.VISIBLE);

                }
            }
        });

        mAdapter.addHeaderView(friendHeadView);
    }

    /**
     * 刷新界面
     */
    private void refresh() {
        loadFriendList();
        refreshLayout.finishRefresh();
    }

    /**
     * 快速回复
     *
     * @param adapter
     * @param friend
     */
    public void quickReplay(BaseQuickAdapter adapter, Friend friend) {
        if (friend.getRoomFlag() != 0) {
            // 用户可能不在群组里，
            int status = friend.getGroupStatus();
            if (1 == status) {
                ToastUtil.showToast(getContext(), R.string.tip_been_kick);
                return;
            } else if (2 == status) {
                ToastUtil.showToast(getContext(), R.string.tip_disbanded);
                return;
            } else if (3 == status) {
                ToastUtil.showToast(getContext(), R.string.tip_group_disable_by_service);
                return;
            }
        }
        if (!coreManager.isLogin()) {
            ToastUtil.showToast(getContext(), R.string.tip_xmpp_offline);
            return;
        }
        // TODO: hint是上一条消息，如果有草稿可能会是草稿，
        CharSequence content;
        if (friend.getType() == XmppMessage.TYPE_TEXT) {// 文本消息 表情
            String s = StringUtils.replaceSpecialChar(friend.getContent());
            content = HtmlUtils.transform200SpanString(s.replaceAll("\n", "\r\n"), true);
            // TODO: 这样匹配的话正常消息里的&8824也会被替换掉，
//            if (content.toString().contains("&8824")) {// 草稿
//                content = content.toString().replaceFirst("&8824", "");
//
//            }
        } else {
            content = HtmlUtils.addSmileysToMessage(
                    ChatMessage.getSimpleContent(getContext(), friend.getType(), friend.getContent()),
                    false
            );

        }
        DialogHelper.verify(
                requireActivity(),
                getString(R.string.title_replay_place_holder, !TextUtils.isEmpty(friend.getRemarkName()) ? friend.getRemarkName() : friend.getNickName()), content,
                new VerifyDialog.VerifyClickListener() {
                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void send(String str) {
                        if (TextUtils.isEmpty(str)) {
                            ToastUtil.showToast(requireContext(), R.string.tip_replay_empty);
                            return;
                        }
                        if (!coreManager.isLogin()) {
                            Reporter.unreachable();
                            ToastUtil.showToast(requireContext(), R.string.tip_xmpp_offline);
                            return;
                        }
                        RoomMember member = RoomMemberDao.getInstance().getSingleRoomMember(friend.getRoomId(), friend.getOwnerId());
                        // 判断禁言状态，
                        if (member != null && member.getRole() == 3) {// 普通成员需要判断是否被禁言
                            if (friend.getRoomTalkTime() > (System.currentTimeMillis() / 1000)) {
                                ToastUtil.showToast(getContext(), InternationalizationHelper.getString("HAS_BEEN_BANNED"));
                                return;
                            }
                        } else if (member == null) {// 也需要判断是否被禁言
                            if (friend.getRoomTalkTime() > (System.currentTimeMillis() / 1000)) {
                                ToastUtil.showToast(getContext(), InternationalizationHelper.getString("HAS_BEEN_BANNED"));
                                return;
                            }
                        }
                        ChatMessage message = new ChatMessage();
                        // 文本类型，抄自，
                        // com.sk.weichat.ui.message.ChatActivity.sendText
                        // com.sk.weichat.ui.message.MucChatActivity.sendText
                        // 黑名单没考虑，正常情况黑名单会删除会话，
                        message.setType(XmppMessage.TYPE_TEXT);
                        message.setFromUserId(friend.getOwnerId());
                        message.setFromUserName(coreManager.getSelf().getNickName());
                        message.setContent(str);
                        // 获取阅后即焚状态(因为用户可能到聊天设置界面 开启/关闭 阅后即焚，所以在onResume时需要重新获取下状态)
                        int isReadDel = PreferenceUtils.getInt(getContext(), Constants.MESSAGE_READ_FIRE + friend.getUserId() + friend.getOwnerId(), 0);
                        message.setIsReadDel(isReadDel);
                        if (1 != friend.getRoomFlag()) {
                            PrivacySetting privacySetting = PrivacySettingHelper.getPrivacySettings(requireContext());
                            boolean isSupport = privacySetting.getMultipleDevices() == 1;
                            if (isSupport) {
                                message.setFromId("youjob");
                            } else {
                                message.setFromId("youjob");
                            }
                        }
                        if (1 == friend.getRoomFlag()) {
                            // 是群聊，
                            message.setToUserId(friend.getUserId());
                            if (friend.getChatRecordTimeOut() == -1 || friend.getChatRecordTimeOut() == 0) {// 永久
                                message.setDeleteTime(-1);
                            } else {
                                long deleteTime = TimeUtils.sk_time_current_time() + (long) (friend.getChatRecordTimeOut() * 24 * 60 * 60);
                                message.setDeleteTime(deleteTime);
                            }
                        } else if (friend.getIsDevice() == 1) {
                            message.setToUserId(friend.getOwnerId());
                            message.setToId(friend.getUserId());
                            // 我的设备消息不过期？
                        } else {
                            message.setToUserId(friend.getUserId());

                            // sz 消息过期时间
                            if (friend.getChatRecordTimeOut() == -1 || friend.getChatRecordTimeOut() == 0) {// 永久
                                message.setDeleteTime(-1);
                            } else {
                                long deleteTime = TimeUtils.sk_time_current_time() + (long) (friend.getChatRecordTimeOut() * 24 * 60 * 60);
                                message.setDeleteTime(deleteTime);
                            }
                        }
                        PrivacySetting privacySetting = PrivacySettingHelper.getPrivacySettings(requireContext());
                        boolean isEncrypt = privacySetting.getIsEncrypt() == 1;
                        if (isEncrypt) {
                            message.setIsEncrypt(1);
                        } else {
                            message.setIsEncrypt(0);
                        }
                        message.setReSendCount(ChatMessageDao.fillReCount(message.getType()));
                        message.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));
                        message.setTimeSend(TimeUtils.sk_time_current_time());
                        // 消息保存在数据库，
                        ChatMessageDao.getInstance().saveNewSingleChatMessage(message.getFromUserId(), message.getToUserId(), message);
                        for (Friend mFriend : mFriendList) {
                            if (mFriend.getUserId().equals(friend.getUserId())) {
                                if (1 == friend.getRoomFlag()) {
                                    coreManager.sendMucChatMessage(message.getToUserId(), message);
                                    mFriend.setContent(message.getFromUserName() + ": " + message.getContent());
                                } else {
                                    if (mFriend.getStatus() != Friend.STATUS_FRIEND && mFriend.getStatus() != Friend.STATUS_SYSTEM && mFriend.getReplyStatus() == Friend.STATUS_REPLAY_NONE) {//未回复消息，即打招呼消息
                                        if (message.getType() == XmppMessage.TYPE_VOICE || message.getType() == XmppMessage.TYPE_IMAGE
                                                || message.getType() == XmppMessage.TYPE_VIDEO || message.getType() == XmppMessage.TYPE_FILE
                                                || message.getType() == XmppMessage.TYPE_LOCATION) {// 语音、图片、视频、文件不能发送
                                            return;
                                        } else {
                                            message.setMsgType(ChatMessage.TYPE_HELLO);
                                        }
                                    } else if (mFriend.getStatus() != Friend.STATUS_FRIEND && mFriend.getStatus() != Friend.STATUS_SYSTEM
                                            && mFriend.getReplyStatus() == Friend.STATUS_REPLAY_SINGLE) {//对方已经单方面发送了打招呼消息
                                        message.setMsgType(ChatMessage.TYPE_HELLO);
                                    }
                                    coreManager.sendChatMessage(message.getToUserId(), message);
                                    mFriend.setContent(message.getContent());
                                }
                                // 清除小红点，
                                clearSingleMessageNum(friend);
                                adapter.notifyDataSetChanged();
                                break;
                            }
                        }
                    }
                });
    }

    /**
     * 加载好友数据
     */
    private void loadFriendList() {
        if (mItemList != null) {
            mItemList.clear();
        }
        mUnReplyList.clear();
        mNewFriendList.clear();

        //关系通知—获取关系通知未读条数
        Friend newFriend = FriendDao.getInstance().getFriend(coreManager.getSelf().getUserId(), Friend.ID_NEW_FRIEND_MESSAGE);
        //关系通知—获取关系通知内容和时间
        List<NewFriendMessage> friends = NewFriendDao.getInstance().getAllNewFriendMsg(coreManager.getSelf().getUserId());
        if (newFriend != null) {
            if (friends != null && friends.size() != 0) {
                newFriend.setContent(getNewFriendContent(friends.get(0)));
                newFriend.setStatus(friends.get(0).getState());
                newFriend.setNickName(friends.get(0).getNickName());
                newFriend.setTimeSend(friends.get(0).getTimeSend());
                mNewFriendList.add(newFriend);
                FriendDao.getInstance().updateFriendInfo(newFriend);
            } else {
                newFriend.setContent("暂无关系通知");
                newFriend.setUnReadNum(0);
                newFriend.setTimeSend(0);
                FriendDao.getInstance().updateFriendInfo(newFriend);
            }

        }

        //群通知
        Friend groupFriend = FriendDao.getInstance().getFriend(coreManager.getSelf().getUserId(), Friend.ID_GROUP_NOTIFICATION);
        int unReadNumTotal = GroupMessageDao.getInstance().getGroupMsgUnReadNumTotal(coreManager.getSelf().getUserId());
        GroupMessage groupMessage = GroupMessageDao.getInstance().getLastGroupMessage(coreManager.getSelf().getUserId());

        if (groupFriend != null && groupMessage != null) {
            String roomName = TextUtils.isEmpty(groupMessage.getRoomName()) ? "群" : groupMessage.getRoomName();
            groupFriend.setNickName(roomName);
            String content = GroupMessageDao.getInstance().getLastGroupMessageContent(groupMessage);
            groupFriend.setContent(content);
            groupFriend.setUnReadNum(unReadNumTotal);
            groupFriend.setTimeSend(groupMessage.getTimeSend());
            FriendDao.getInstance().updateFriendInfo(groupFriend);
        } else if (groupFriend != null) {
            groupFriend.setContent("暂无群通知");
            groupFriend.setUnReadNum(0);
            groupFriend.setTimeSend(0);
            FriendDao.getInstance().updateFriendInfo(groupFriend);
        }

        //打招呼通知
        mFriendList = FriendDao.getInstance().getAllFriendMsg(coreManager.getSelf().getUserId());
        List<Friend> mRemoveFriend = new ArrayList<>();
        if (mFriendList.size() > 0) {
            for (int i = 0; i < mFriendList.size(); i++) {
                Friend friend = mFriendList.get(i);
                if (friend != null) {
                    //删除发给自己的消息
                    if (friend.getUserId().equals(coreManager.getSelf().getUserId())
                            || friend.getIsBeBlack() == 1) {
                        Log.e("lzs", "getIsBeBlack");
                        mRemoveFriend.add(friend);

                    } else if (friend.getStatus() != Friend.STATUS_SYSTEM && friend.getStatus() != Friend.STATUS_FRIEND
                            && friend.getReplyStatus() == Friend.STATUS_REPLAY_SINGLE) {
                        //非系统、非好友且是对方发给来的未回复消息，则为招呼消息
                        mUnReplyList.add(friend);
                    } else if (friend.getStatus() != Friend.STATUS_SYSTEM && friend.getStatus() != Friend.STATUS_FRIEND
                            && friend.getReplyStatus() == Friend.STATUS_REPLAY_NONE) {

                        //未回复的消息
                        ChatMessage message = ChatMessageDao.getInstance().getLastChatMessage(coreManager.getSelf().getUserId(), friend.getUserId());
                        if (message != null && !message.isMySend() && message.getType() != XmppMessage.TYPE_TIP) {
                            //对方发过来的非招呼消息，则为已经回复的消息
                            FriendDao.getInstance().updateFriendReplyStatus(coreManager.getSelf().getUserId(), friend.getUserId(), Friend.STATUS_REPLAY_BOTH);
                        }
                    }
                }
            }
            mFriendList.removeAll(mRemoveFriend);
            mFriendList.removeAll(mUnReplyList);
            for (Friend friend : mFriendList) {
                if (friend.getRoomFlag() == 1) {
                    try {
                        List<String> idList = RoomMemberDao.getInstance().getRoomMemberForAvatar(friend.getRoomId(), coreManager.getSelf().getUserId());
                        if (idList == null || idList.size() == 0) {
                            loadRoomMembers(friend.getRoomId());
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }

            }
        }

        boolean isTop = true;
        for (int i = 0; i < mFriendList.size(); i++) {
            MyMultipleItem item = new MyMultipleItem();
            Friend friend = mFriendList.get(i);
            //打招呼消息
            if (isTop && friend.getTopTime() == 0 //非置顶消息
                    && mUnReplyList.size() > 0
                    && mUnReplyList.get(0).getTimeSend() > friend.getTimeSend()) {
                isTop = false;
                item.setItemType(MyMultipleItem.CALL_TYPE);//添加打招呼消息item
            } else if (friend.getUserId().equals(Friend.ID_GROUP_NOTIFICATION)) {
                //群通知
                item.setItemType(MyMultipleItem.GROUP_TYPE);//添加群消息item
            } else if (friend.getUserId().equals(Friend.ID_NEW_FRIEND_MESSAGE)) {
                //关系通知
                item.setItemType(MyMultipleItem.RELATION_TYPE);//添加关系消息item
            } else {
                item.setItemType(MyMultipleItem.NORMAL_TYPE);//

            }
            item.setData(friend);
            //设置时间进行排序
            item.setTime(friend.getTimeSend());
            item.setTopTime(friend.getTopTime());
            mItemList.add(item);
        }
        if (isTop) {
            if (mUnReplyList.size() > 0) {
                mItemList.add(new MyMultipleItem(MyMultipleItem.CALL_TYPE, null));//添加打招呼消息item
            }
        }
        //钱包通知
        mItemList.add(setupWalletItem());
        Collections.sort(mItemList);

        mAdapter.notifyDataSetChanged();

    }

    Gson gson = new Gson();

    /**
     * 组装钱包通知数据
     *
     * @return
     */
    private MyMultipleItem setupWalletItem() {
        MyMultipleItem item = new MyMultipleItem(MyMultipleItem.WALLET_TYPE);
        //钱包通知
        item.setMsg_title(getResources().getString(R.string.wallet_notification_title));
        //查询是否有未读红包通知
        List<RedPacketNoticeBean> list = RedPacketNoticeDao.getInstance().queryAll();
        if (list.size() == 0) {
            item.setMsg_content(getResources().getString(R.string.tips_no_wallet_msg));
        } else {
            boolean hasUnreadMsg = false;
            int unReadCount = 0;
            for (int i = 0; i < list.size(); i++) {
                if (!hasUnreadMsg && list.get(i).getIsRead() == RedPacketNoticeBean.unRead) {
                    unReadCount++;
                    hasUnreadMsg = true;
                    RedPacketNoticeInfoBean redPacketNoticeInfoBean;
                    try {
                        //Log.e("lzs", "钱包通知 ObjectId:" + bean.getObjectId());
                        redPacketNoticeInfoBean = gson.fromJson(list.get(i).getObjectId(), RedPacketNoticeInfoBean.class);
                        if (redPacketNoticeInfoBean != null) {
                            item.setMsg_content(redPacketNoticeInfoBean.getTitle() + "通知");
                        }
                        //时间
                        item.setTime(list.get(i).getTimeSend());
                    } catch (Exception e) {

                    }
                } else if (list.get(i).getIsRead() == RedPacketNoticeBean.unRead) {
                    unReadCount++;
                }
            }
            //设置未读数量
            item.setCount(unReadCount);
            if (!hasUnreadMsg) {
                RedPacketNoticeInfoBean redPacketNoticeInfoBean = gson.fromJson(list.get(0).getObjectId(), RedPacketNoticeInfoBean.class);
                item.setMsg_content(redPacketNoticeInfoBean.getTitle() + "通知");
                item.setTime(list.get(0).getTimeSend());
            }
        }
        return item;
    }

    /**
     * 找到消息通知数据的下标
     */
    private int findWalletItemPosition(List<MyMultipleItem> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getItemType() == MyMultipleItem.WALLET_TYPE) {
                return i;
            }
        }
        return -1;
    }


    private String getNewFriendContent(NewFriendMessage newFriendMessage) {
        String content = "";
        switch (newFriendMessage.getState()) {
            case Friend.STATUS_20://默认值什么都不显示

                break;
            case Friend.STATUS_10://显示  等待验证
                content = InternationalizationHelper.getString("JXFriendObject_WaitPass");
                break;
            case Friend.STATUS_11: //被关注
                content = newFriendMessage.getNickName() + getActivity().getString(R.string.attention_me);
                break;
            case Friend.STATUS_12: //已通过验证
                content = InternationalizationHelper.getString("JXFriendObject_Passed");
                break;
            case Friend.STATUS_13: //验证被通过了
                content = InternationalizationHelper.getString("JXFriendObject_PassGo");
                break;
            case Friend.STATUS_14://别人回话
                content = newFriendMessage.getContent();
                break;
            case Friend.STATUS_15://回话
                content = newFriendMessage.getContent();
                break;
            case Friend.STATUS_16://已删除了XXX
                content = InternationalizationHelper.getString("JXAlert_DeleteFirend") + newFriendMessage.getNickName();
                break;
            case Friend.STATUS_17://XXX删除了我
                content = newFriendMessage.getContent() + getActivity().getString(R.string.delete_me);
                break;
            case Friend.STATUS_18://已拉黑了XXX
                content = "你拉黑了" + newFriendMessage.getNickName();
                break;
            case Friend.STATUS_19://XXX拉黑了你
                content = newFriendMessage.getNickName() + "拉黑了你";
                break;
            case Friend.STATUS_21://XXX 添加你为好友
                content = newFriendMessage.getNickName() + getActivity().getString(R.string.add_me_as_friend);
                break;
            case Friend.STATUS_22://你添加好友 XXX
                Friend privateFriend = FriendDao.getInstance().getFriend(newFriendMessage.getOwnerId(), newFriendMessage.getUserId());
                if (privateFriend != null && privateFriend.getStatus() == Friend.STATUS_SYSTEM) {
                    content = getActivity().getString(R.string.added_notice_friend) + newFriendMessage.getNickName();
                } else {
                    content = getActivity().getString(R.string.added_friend) + newFriendMessage.getNickName();
                }
                break;
            case Friend.STATUS_24://XXX把你移出黑名单
                content = newFriendMessage.getNickName() + "把你移出黑名单";
                break;
            case Friend.STATUS_25://通过手机联系人添加
                content = "通过手机联系人加为好友";
                break;
            case Friend.STATUS_26://被后台删除的好友，仅用于新的好友页面显示，
                content = newFriendMessage.getContent();
                break;

            case Friend.STATUS_27://你取关了XXX，解除好友关系
                content = "你取关了" + newFriendMessage.getNickName() + "，解除好友关系";
                break;

            case Friend.STATUS_28://XXX取关了你，解除好友关系
                content = newFriendMessage.getNickName() + "取关了你，解除好友关系";
                break;

            case Friend.STATUS_29://你把XXX移出黑名单
                content = "你把" + newFriendMessage.getNickName() + "移出黑名单";
                break;
            case Friend.STATUS_30://你移粉你，解除好友关系
                content = newFriendMessage.getNickName() + "移粉你，解除好友关系";
                break;

            case Friend.STATUS_31://你移粉XX，解除好友关系
                content = "你移除" + newFriendMessage.getNickName() + "粉丝，解除好友关系";
                break;
        }
        return content;
    }

    /**
     * 加载群成员
     *
     * @param roomId 群房间号
     */
    private void loadRoomMembers(final String roomId) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", roomId);
        params.put("pageSize", Constants.MUC_MEMBER_PAGE_SIZE);
        HttpUtils.get().url(coreManager.getConfig().ROOM_GET)
                .params(params)
                .build()
                .execute(new BaseCallback<MucRoom>(MucRoom.class) {

                             @Override
                             public void onResponse(ObjectResult<MucRoom> result) {
                                 if (result.getResultCode() == 1 && result.getData() != null) {
                                     final MucRoom mucRoom = result.getData();
                                     updateRoomMembers(mucRoom);
                                 } else {
                                     ToastUtil.showErrorData(getContext());
                                 }
                             }

                             @Override
                             public void onError(Call call, Exception e) {
                                 ToastUtil.showNetError(getContext());
                             }
                         }
                );
    }

    /**
     * 更新群成员到本地数据库
     *
     * @param mucRoom
     */
    private void updateRoomMembers(MucRoom mucRoom) {
        // 更新部分群属性
        MyApplication.getInstance().saveGroupPartStatus(mucRoom.getJid(), mucRoom.getShowRead(), mucRoom.getAllowSendCard(),
                mucRoom.getAllowConference(), mucRoom.getAllowSpeakCourse(), mucRoom.getTalkTime());
        PreferenceUtils.putBoolean(MyApplication.getContext(),
                Constants.IS_NEED_OWNER_ALLOW_NORMAL_INVITE_FRIEND + mucRoom.getJid(), mucRoom.getIsNeedVerify() == 1);
        PreferenceUtils.putBoolean(MyApplication.getContext(),
                Constants.IS_ALLOW_NORMAL_SEND_UPLOAD + mucRoom.getJid(), mucRoom.getAllowUploadFile() == 1);
        List<RoomMember> roomMemberList = new ArrayList<>();
        for (int i = 0; i < mucRoom.getMembers().size(); i++) {
            RoomMember roomMember = new RoomMember();
            roomMember.setRoomId(mucRoom.getId());
            roomMember.setUserId(mucRoom.getMembers().get(i).getUserId());
            roomMember.setUserName(mucRoom.getMembers().get(i).getNickName());
            if (TextUtils.isEmpty(mucRoom.getMembers().get(i).getRemarkName())) {
                roomMember.setCardName(mucRoom.getMembers().get(i).getNickName());
            } else {
                roomMember.setCardName(mucRoom.getMembers().get(i).getRemarkName());
            }
            roomMember.setRole(mucRoom.getMembers().get(i).getRole());
            roomMember.setCreateTime(mucRoom.getMembers().get(i).getCreateTime());
            roomMemberList.add(roomMember);
        }
        AsyncUtils.doAsync(this, mucChatActivityAsyncContext -> {
            for (int i = 0; i < roomMemberList.size(); i++) {// 在异步任务内存储
                RoomMemberDao.getInstance().saveSingleRoomMember(mucRoom.getId(), roomMemberList.get(i));
            }
        });
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mAdapter.notifyDataSetChanged();
            }
        }, 1000);

    }

    /**
     * 清除单个聊天对象的未读消息
     *
     * @param friend 聊天对象
     */
    private void clearSingleMessageNum(Friend friend) {
        friend.setUnReadNum(0);
        FriendDao.getInstance().markUserMessageRead(coreManager.getSelf().getUserId(), friend.getUserId());
        MainActivity mMainActivity = (MainActivity) getActivity();
        if (mMainActivity != null) {
            mMainActivity.updateNumData();
        }
        mAdapter.notifyDataSetChanged();

    }

    /**
     * 清除未读消息弹框
     */
    private void showClearUnReadDialog() {

        List<Friend> allUpReplyList = new ArrayList<>();//未读招呼消息总数
        for (Friend friend : mUnReplyList) {
            if (friend.getUnReadNum() > 0) {
                allUpReplyList.add(friend);
            }
        }
        List<Friend> allUpReplyMessageList = new ArrayList<>();//未读好友列表消息总数
        for (Friend friend : mFriendList) {
            if (friend.getUnReadNum() > 0) {
                allUpReplyMessageList.add(friend);
            }
        }
        List<Friend> allUpReplyInformList = new ArrayList<>();//未读通知列表消息总数
        for (Friend friend : mNewFriendList) {
            if (friend.getUnReadNum() > 0) {
                allUpReplyInformList.add(friend);
            }
        }
        if (allUpReplyList.size() == 0 && allUpReplyMessageList.size() == 0 && allUpReplyInformList.size() == 0) {
            ToastUtil.showToast(getActivity(), "无未读消息要清空");
        } else {
            SelectionFrame mSF = new SelectionFrame(getActivity());
            mSF.setSomething(getString(R.string.dialog_title), getString(R.string.msg_clear_unread), new SelectionFrame.OnSelectionFrameClickListener() {
                @Override
                public void cancelClick() {

                }

                @Override
                public void confirmClick() {
                    clearAllMessageNum();
                }
            });
            mSF.show();
        }
    }

    /**
     * 清除所有未读消息
     */
    private void clearAllMessageNum() {

        //清除招呼消息
        for (Friend friend : mUnReplyList) {
            friend.setUnReadNum(0);
            FriendDao.getInstance().markUserMessageRead(coreManager.getSelf().getUserId(), friend.getUserId());
        }
        //清除群通知
        GroupMessageDao.getInstance().markUserMessageRead(coreManager.getSelf().getUserId());
        //清除好友列表消息
        for (Friend friend : mFriendList) {
            friend.setUnReadNum(0);
            FriendDao.getInstance().markUserMessageRead(coreManager.getSelf().getUserId(), friend.getUserId());
        }
        //清除关系通知
        FriendDao.getInstance().markUserMessageRead(coreManager.getSelf().getUserId(), Friend.ID_NEW_FRIEND_MESSAGE);
        MsgBroadcast.broadcastMsgUiUpdate(getActivity());

        //清楚钱包和红包通知
        List<RedPacketNoticeBean> list = RedPacketNoticeDao.getInstance().queryUnRead();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setIsRead(1);
            RedPacketNoticeDao.getInstance().update(list.get(i));
        }
        mItemList.get(findWalletItemPosition(mItemList)).setCount(0);
        Collections.sort(mItemList);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * XMPP手动重连
     *
     * @return
     */
    public boolean hardLine() {
        int authState = XmppConnectionManager.mXMPPCurrentState;
        if (authState == 2) {
            return false;
        }

        if (!coreManager.isServiceReady()) {
            // 小米手机在后台运行时，CoreService经常被系统杀死，需要兼容ta
            Log.e("zq", "CoreService为空，重新绑定");
            coreManager.relogin();
        } else {
            MainActivity mActivity = (MainActivity) getActivity();
            if (mActivity != null) {
                coreManager.autoReconnectShowProgress(mActivity);
            } else {
                Log.e("zq", "mActivity==null");
            }
        }
        return true;
    }

    /**
     * 加载换一换功能用户列表数据
     */
    private void loadUnKnowUserList() {

        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);

        HttpUtils.get().url(coreManager.getConfig().USERLIST_UNKNOW_URL)
                .params(params)
                .build()
                .execute(new BaseCallback<User[]>(User[].class) {

                    @Override
                    public void onResponse(ObjectResult<User[]> result) {

                        if (Result.checkSuccess(getActivity(), result)) {
                            mHeadFriendList.clear();
                            User[] users = result.getData();
                            for (int i = 0; i < users.length; i++) {
                                mHeadFriendList.add(users[i]);
                            }
                            if (mHeadFriendList.size() > 0) {
                                headContent.setVisibility(View.VISIBLE);
                                headArrow.setEnabled(true);
                                headArrow.setBackgroundResource(R.drawable.imessage_icon_arrow);
                                headChange.setVisibility(View.VISIBLE);
                            } else {
                                headContent.setVisibility(View.GONE);
                                headArrow.setEnabled(false);
                                headArrow.setBackgroundResource(R.drawable.imessage_icon_arrow2);
                                headChange.setVisibility(View.GONE);
                            }
                            mFriendHeadAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showNetError(getActivity());
                    }
                });
    }

    public void onNewIntentRefresh() {
        refreshLayout.autoRefresh();
    }
}
